import java.util.HashMap;
import java.util.Map;

//和为 K 的子数组
//测试链接 https://leetcode.cn/problems/subarray-sum-equals-k/description/
public class SubarraySum {
    public int subarraySum(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0,1);

        int ret = 0, sum = 0;
        for(int num : nums){
            sum += num; //计算前缀和
            ret += map.getOrDefault(sum - k, 0); //统计结果
            map.put(sum, map.getOrDefault(sum,0) + 1);
        }
        return ret;
    }
}
